package com.ccg.service;

import com.ccg.dao.UserDao;
import com.ccg.entity.Message;
import com.ccg.entity.Permission;
import com.ccg.entity.User;
import com.ccg.entity.User_Role;
import com.ccg.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private BCryptPasswordEncoder encoder;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleService roleService;

    //分页查找所有用户
    public PageBean<User> findAllUser(int currPage){
        HashMap<String, Object> map = new HashMap<>();//哈希集合存储不重复的数据
        PageBean<User> pageBean = new PageBean<>();
        //每页显示的数据
        int pageSize = 10;
        pageBean.setPageSize(pageSize);

        //封装总记录数
        int totalCount = userDao.getUserNumber();
        pageBean.setTotalCount(totalCount);
        //如果没有数据,直接返回
        if(totalCount==0){
            return pageBean;
        }
        //封装总页数
        double tc = totalCount;
        Double num = Math.ceil(tc / pageSize);//向上取整
        pageBean.setTotalPage(num.intValue());

        //传入的当前页小于1时则等于1，大于总页数则等于总页数也就是最后一页
        if(currPage<1) currPage=1;
        else if(currPage>pageBean.getTotalPage()) currPage = pageBean.getTotalPage();

        //封装当前页数
        pageBean.setCurrPage(currPage);
        map.put("start", (currPage - 1) * pageSize);
        map.put("size", pageBean.getPageSize());
        //封装每页显示的数据
        List<User> lists = userDao.findAllUser(map);
        for(User user:lists){
            user.setPassword("");
        }
        pageBean.setLists(lists);

        return pageBean;
    }
    public User findUserById(int u_id) {
        return userDao.findUserById(u_id);
    }

    //根据用户账号username精确查找用户信息
    public User findUserByUsername(String username) {
        return userDao.findUserByUsername(username);
    }

    //根据用户电子邮箱email精确查找用户信息
    public User findUserByEmail(String email) {
        return userDao.findUserByEmail(email);
    }

    //根据用户账号username查找用户权限标识,security登陆时调用
    public List<Permission> findPermsByUsername(String username) {
        return userDao.findPermsByUsername(username);
    }

    //查找所有被冻结的用户
    public Message findAllLocked() {
        return new Message(0,"查找冻结用户成功",userDao.findAllLocked());
    }
    //对用户进行冻结或者解冻
    public Message updateLocked(User user){
        Message message;
        if(user.getU_id()==1||user.getU_id()==0){
            if(userDao.updateLocked(user)==1) {
                if(user.getU_id()==0) {
                    message = new Message(0, "成功冻结" + user.getUsername() + "用户", null);
                }
                else message = new Message(0, "成功解冻结" + user.getUsername() + "用户", null);
            }
            else message = new Message(1,"操作失败","该账户不存在");
        }
        else message = new Message(1,"操作失败","数据异常");
        return message;
    }
    //根据用户账号修改用户密码
    //其中password作为密码验证,realname作为新密码
    //返回1修改密码成功,0失败
    public Message updatePasswByUsername(User user) {
        //判断用户输入密码是否成功
        if(encoder.matches(user.getPassword(),userDao.findPassword(user.getUsername()))) {
            //对新密码进行加密
            user.setRealname(encoder.encode(user.getRealname()));
            if(userDao.updatePasswByUsername(user)==1)
                return new Message(0,"修改密码成功","请重新登录");
        }
        return new Message(1,"修改密码失败","原密码错误");
    }
    public Message updateEmail(User user){
        try {
            //判断用户输入密码是否成功
            if (encoder.matches(user.getPassword(), userDao.findPassword(user.getUsername()))) {
                if(userDao.updateEmail(user)==1) return new Message(0,"修改新邮箱地址成功",null);
                else return new Message(1,"修改新邮箱地址失败","意外错误");
            }
        }catch (DuplicateKeyException e){
            return new Message(1,"修改新邮箱地址失败","该邮箱地址已被注册");
        }
        return new Message(1,"修改新邮箱地址失败","密码错误");
    }
    public Message updateRealName(User user){
        if(userDao.updateRealName(user)==1)return new Message(0,"修改真实姓名成功",null);
        else return new Message(1,"修改真实姓名失败","意外错误");
    }
    //添加一个用户，并赋予普通用户权限
    @Transactional
    public Message addUser(User user) {
        try {
            user.setPassword(encoder.encode(user.getPassword()));
            //添加用户并判断是否成功
            if (userDao.addUser(user) == 1) {
                User_Role user_role = new User_Role();
                user_role.setU_id(user.getU_id());
                user_role.setR_id(2);
                //根据插入成功返回的主键向该用户授予普通角色权限
                roleService.addCommonRoleByU_id(user_role);
                return new Message(0,"注册账户成功","请登录");
            }
        }catch (DuplicateKeyException e){
            System.out.println("该账号或者邮箱地址已被注册");
            return new Message(1,"注册账户失败","该账号或者邮箱地址已被注册");
        }
        return new Message(1,"注册账户失败","意外错误");
    }
    //将最后一次登陆时间设置为当前时间,在登陆成功时调用
    public int updateLastLogin(String username) {
        return userDao.updateLastLogin(username);
    }

    //统计
    //获取该日期区间登陆的用户的数量
    public int getUserCountInDate(HashMap<String, Object> map){
        return userDao.getUserCountInDate(map);
    }
}
